package pure.engine.model 
{
	import flash.net.registerClassAlias;
	import pure.debug.Logger;
	import pure.engine.core.IFrameListener;
	import pure.engine.core.ProcessManager;
	import pure.engine.core.ns_despair;
	import pure.utils.DesU;
	
	use namespace ns_despair;
	
	/**
	 * 实体管理器
	 * [Author] - PURE
	 * 
	 */
public class EntityManager
{


	/**
	 * 获取同一名字的实体列表
	 * 
	 * @param name
	 */
	ns_despair static function getEntitiesByName(name:String):Array 
	{
		if (m_entityGroups[name]) 
		{
			return m_entityGroups[name].concat();
		}
		return [];
	}
	
	
	/**
	 * 获取匹配名字的实体列表
	 * 
	 * @param names
	 */
	ns_despair static function getEntitiesByNames(names:Array):Array 
	{
		var result:Array, list:Array;
		var len:int, i:int;
		var name:String;
		
		len = names.length;
		for (i = 0; i < len; i++)
		{
			name = names[i];
			list = getEntitiesByName(name);
			if (list) 
			{
				if (result) 
				{
					result = [];
				}
				result.push.apply(result, list);
			}
		}
		return result;
	}

	
   /**
	* 注册
	* 
	* @param entity
	*/
	ns_despair static function register(E:Entity):void
	{
		var group:Array;
		
		if (!m_entityGroups[E.name]) 
		{
			m_entityGroups[E.name] = [];
		}
		
		group =  m_entityGroups[E.name];
		
		group.push(E);
		m_numAlive++;
	}	
	 
	
	/**
	 * 注销
	 * 
	 * [Param] - entity
	 */
	ns_despair static function unregister(E:Entity):void 
	{	
		var group:Array;
		var index:int;
		
		group  =  m_entityGroups[E.name];
		index  =  group.indexOf(E);
		
		group.splice(index, 1);
		m_numAlive--;
	}
	
	
	/**
	 * 注册成品实体
	 * 
	 * [Param] - args
	 */
	ns_despair static function registerEntities(args:Array):void
	{
		var factoryName:String;
		var factoryType:Class;
		var len:int, i:int;
		
		trace('\n----------------------------------- [Entity] -----------------------------------');
		len = args.length
		while (i < len)
		{
			factoryType  =  args[i++];
			factoryName  =  DesU.getClassName(factoryType);
			
			registerClassAlias(factoryName, factoryType);
			Logger.reportMessage('EntityManager', '实体 (' + factoryName + ') 注册完成.');
		}
	}
	
	
	
	
	//======================
	// Member
	//======================
	

	ns_despair static var m_entityGroups:Object  =  { };  // 实体组

	ns_despair static var m_dirtyEntityList:Vector.<Entity> = Vector.<Entity>([null]);  // 第一项为空
	
	ns_despair static var m_numAlive:int;  // 活着的实体总数

	
}

}